﻿

TT.NewTournament = {};

TT.NewTournament.Init = function () {
    TT.NewTournament.InitStartButton();
    TT.NewTournament.InitCancelButton();
    TT.NewTournament.LoadPlayerList(); 
}


TT.NewTournament.LoadPlayerList = function () {
    
    $.get('/admin/getplayers', function (response) {
        
        allPlayers = response;
       
        if (allPlayers.length) {
            var $playerList = $('<ul />').addClass("player-list");
            var playerName, 
                playerId;

            $(allPlayers).each(function () {
                playerId = $(this)[0].id;
                playerName = $(this)[0].label;
                playerAvatar = '/img/_tmp/'+ playerId +'.jpg';
                var $playerButtonContainer = $('<li/>');
                var $playerButton = $('<a/>').appendTo($playerButtonContainer);
                $playerButton.text(playerName)
                             .data("player-id", playerId);
                var $playerAvatarImage = $('<img/>').attr("src", playerAvatar).prependTo($playerButton);
                $playerButton.on("click", function () {
                    TT.NewTournament.TogglePlayer($(this));
                });
                $playerButtonContainer.appendTo($playerList);
            });

            $("#player-select").append($playerList);
        } else {
            $("#player-select").html("<p>There are no users in the system, add some in user management.</p>");
        }
    });
}

TT.NewTournament.TogglePlayer = function( el ){
    $(el).toggleClass("selected");
    if($(".player-list").find("a.selected").length > 1){
        $(TT.NewTournament.StartButton).fadeIn(200);
    }else{
        $(TT.NewTournament.StartButton).fadeOut(200);
    }
}

TT.NewTournament.InitStartButton = function () {
 
    TT.NewTournament.StartButton = $("#start-tournament").hide();
 
    $(this.StartButton).on("click", function (e) {
        e.preventDefault();
        TT.NewTournament.CancelButton.css({"display": "block"}).animate({"opacity": 1}, 200);
        TT.NewTournament.Start();
    });
}

TT.NewTournament.InitCancelButton = function(){
    TT.NewTournament.CancelButton = $("#cancel-tournament");
     $(this.CancelButton).on("click", function (e) {
        e.preventDefault();
        window.location.reload(false); 
    });
}

TT.NewTournament.MakeEveryoneDisabled = function(){
    $(".player-list a").unbind("click");
}

TT.NewTournament.Start = function(){
    var $selectedPlayers = $(".player-list").find("a.selected");
    if ($selectedPlayers.length > 1) {
        TT.Common.AddLoadingAnimation($(TT.NewTournament.StartButton), "red");
        TT.NewTournament.MakeEveryoneDisabled();
        var players = new Array();
        $selectedPlayers.each(function () {
            players.push($(this).data("player-id"));
        });
        var playersJson = JSON.stringify(players);

        $.ajax({
            url: '/Admin/Index',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: playersJson,
            success: function (result) {
                window.location.href = result.link;
            }
        });
    }
}



$(function () {
    TT.NewTournament.Init();
});


//$(document).ready(function () {
//    var allPlayers = null;

//    var PlayerModel = function (players) {
//        var self = this;
//        self.players = ko.observableArray(players);

//        self.addPlayer = function () {
//            self.players.push({
//                FullName: "",
//                Id:0
//            });
//            $('input.autocomplete:last').autocomplete(getAutocompleteSettings(allPlayers));
//        };

//        self.removePlayer = function (player) {
//            self.players.remove(player);
//        };

//        self.updatePlayer = function (playerName, id) {

//            var player = ko.utils.arrayFirst(this.players(), function (currentPlayer) {
//                console.log(currentPlayer);
//                return currentPlayer.FullName === playerName;
//            });
//            player.Id = id;
            
//        };

//        self.save = function (form) {
//            var mappedData = ko.utils.arrayMap(self.players(), function (item) {
//                console.log(mappedData);
//                return item.Id;
//            });            
//            $.ajax({
//                url: '/Admin/Index',
//                type: 'POST',
//                contentType: 'application/json; charset=utf-8',
//                data: ko.toJSON(mappedData),
//                success: function (result) {
//                    var successMessage = $('#success-message');
//                    var tournamentLink = successMessage.children('a');
//                    var tournamentIdSpan = tournamentLink.children('span');
//                    tournamentLink.attr('href', result.link);
//                    tournamentIdSpan.text(result.id);
//                    successMessage.show();
//                }
//            });
//        };
//    };

//    var viewModel = new PlayerModel([
//        { FullName:"test", Id:0 }
//    ]);
//    ko.applyBindings(viewModel);

//    function getAutocompleteSettings(data) {
//        return {
//            source: data,
//            select: function (event, ui) {
//                $(event.target).val(ui.item.label);
//                $(event.target).change();
//                viewModel.updatePlayer(ui.item.label, ui.item.id);
//            }
//        };
//    };

//    $.get('/admin/getplayers', function (response) {
//        allPlayers = response;
//        $("input.autocomplete").autocomplete(getAutocompleteSettings(allPlayers));
//    });

//    $("form").validate({ submitHandler: viewModel.save });
//});







